const { blog_user, blog_roles } = require('@/model');
const Response = require('../utils/response')
// 权限控制
module.exports = (requiredPermission)=>{
  return async (ctx, next) => {
    const user = ctx.state.user;
    if (user.role_id === 1) { // 超级管理员
      return await next();
    } else {
      const dbUser = await blog_user.findByPk(user.id, {
        include: [
          {
            model: blog_roles, as: 'role',
          },
        ]
      })
      // 获取用户角色的权限
      const permissions = dbUser.roles.flatMap(role => role.permission_roles.map(p => p.key));
      if (!permissions.includes(requiredPermission)) {
        return Response.error(ctx, '无权限访问', 403);
      }
      await next();
    }
  }
}
